import Taro, { Component, Config, getCurrentPages } from '@tarojs/taro'
import { View, Image, Text, ScrollView } from '@tarojs/components'
import { AtIcon, AtTextarea, AtButton, AtInputNumber, AtForm, AtToast } from 'taro-ui'
import { observer, inject } from '@tarojs/mobx'
import Stores from '../../stores/storeIdentifier'
import './index.scss'
import AuthenticationStore from '../../stores/authenticationStore'
import CartStore from '../../stores/cartStore'
import { ShoppingCartDto } from '../../services/cart/dto/shoppingCartDto'
import { OrderModel } from '../../services/order/dto/orderModel'
import { OrderItemModel } from '../../services/order/dto/orderItemModel'
import { PaymentType } from '../../services/order/dto/paymentType'
import OrderStore from '../../stores/orderStore'
import WxOpenStore from '../../stores/wxOpenStore';
import { UserShippingAddressDto } from '../../services/cart/dto/userShippingAddressDto';


export interface IIndexProps {
  cartStore: CartStore,
  authenticationStore: AuthenticationStore,
  orderStore: OrderStore,
  wxOpenStore: WxOpenStore
}

@inject(Stores.CartStore, Stores.AuthenticationStore, Stores.OrderStore, Stores.WxOpenStore)
@observer
class Index extends Component<IIndexProps> {

  /**
   * 指定config的类型声明为: Taro.Config
   *
   * 由于 typescript 对于 object 类型推导只能推出 Key 的基本类型
   * 对于像 navigationBarTextStyle: 'black' 这样的推导出的类型是 string
   * 提示和声明 navigationBarTextStyle: 'black' | 'white' 类型冲突, 需要显示声明类型
   */
  config: Config = {
    backgroundColor: '#c80d0d',
    navigationBarTitleText: '原谅呗'
  }

  state = {
    isOpened: false
  }

  type: number
  remark: string
  isLogin = false
  totalPrice: number
  cartItems: ShoppingCartDto[]
  cartNowItems: ShoppingCartDto[]
  canShare: boolean = false
  model: OrderModel
  orderId: string
  userShippingAddressId: number
  defaultAddress: UserShippingAddressDto
  constructor(props: any) {
    super(props)
  }

  async componentWillMount() {
    await this.getLoginStatus()
  }

  getLoginStatus = async () => {
    await this.props.authenticationStore.getLoginStatus();
    const { isLogin } = this.props.authenticationStore;
    if (isLogin) {
      await this.getMyShoppingCart();
    } else {
      this.setState(
        {
          showLogin: true
        }
      )
    }
  }

  async getMyShoppingCart() {
    await this.props.cartStore.getMyShoppingCart()
    this.cartItems = this.props.cartStore.cartItems
    let beidong = this.cartItems.filter(m => m.giftType == 0)
    let zhudong = this.cartItems.filter(m => m.giftType == 1)
    if (beidong.length >= zhudong.length) {
      this.cartNowItems = beidong
      this.type = 0
    }
    else {
      this.cartNowItems = zhudong
      this.type = 1
    }

    this.getTotalPrice()
    this.isLogin = true
    this.setState({})
  }
  handleChange = async (item, value, e) => {
    if (value <= 0) {
      await this.props.cartStore.deleteShoppingCarts([item.id]);
      await this.getMyShoppingCart()
    }
    else {
      item.quantity = value

      let sku = this.cartNowItems.find(m => m.id == item.id)
      if (sku) {
        sku.quantity = value
        await this.props.cartStore.updateShoppingCart({ moduleTypeId: sku.moduleTypeId, quantity: value, productId: sku.productId, skuId: sku.skuId, id: sku.id, giftType: this.type })
      }
    }

    this.setState({}, async () => {
      this.getTotalPrice()
    })
  }

  handleRemark = (value, item) => {
    this.remark = value.detail.value
    this.setState({})
  }

  getTotalPrice() {
    this.totalPrice = 0
    this.cartItems.map((item) => {
      this.totalPrice += item.price * item.quantity
    })
    this.totalPrice = parseFloat(this.totalPrice.toFixed(2));
    this.setState({})
  }

  async gotoMall(type) {
    Taro.redirectTo({
      url: '/pages/category/index?type=' + type
    })
  }

  async onClose() {
    this.canShare = false
    await this.getMyShoppingCart()
    this.setState({})
  }

  blurChange() {

  }

  async commit(e) {
    await this.props.wxOpenStore.createFormIds([{ formId: e.detail.formId, formIdType: 0 }])

    if (!Taro.getStorageSync('access_token')) {
      Taro.navigateTo({
        url: '/pages/passport/index',
      })
      return
    }
    if (this.cartNowItems && this.cartNowItems.length) {
      await this.createOrder()
    }
    else {
      Taro.showToast({ title: '请先选择礼品', icon: 'none' })
    }
  }

  async createOrder() {
    if (this.remark) {

    }
    else {
      Taro.showToast({ title: '请填写祝福语', icon: 'none' })
      return
    }

    this.setState({ isOpened: true })
    this.model = new OrderModel()
    this.model.paymentType = PaymentType.Weixin
    this.model.orderItems = []
    this.model.remark = this.remark
    this.model.giftType = this.type
    this.model.userShippingAddressId = this.userShippingAddressId
    this.cartNowItems.map((item) => {
      let oi = new OrderItemModel()
      oi.shoppingCartId = item.id
      oi.productId = item.productId
      oi.quantity = item.quantity
      oi.remark = item.remark
      oi.skuId = item.skuId
      this.model.orderItems.push(oi)
    })
    await this.props.orderStore.createOrder(this.model)
    this.orderId = this.props.orderStore.orderId
    //如果创建订单成功，第一返回上一页，去付款按钮禁用，在此返回购物车移除选中物品
    if (this.orderId) {
      this.remark = '';
      this.getMyShoppingCart()
      this.setState({ isOpened: false })
      this.gotoResult()
    }
  }


  gotoResult() {
    Taro.navigateTo({
      url: '/pages/index/result?id=' + this.orderId + '&type=' + this.type,
    })
  }

  onShareAppMessage() {
    let tmpPath = '/pages/index/index'
    return {
      title: '在犯错这问题上找到了最好的原谅方式...嘿嘿',
      path: tmpPath,
      success: function (res) {
        console.log(res)
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function () {
      }
    }
  }

  async componentDidShow() {
    let pages = getCurrentPages()
    if (pages) {
      let prev = pages[pages.length - 1]

      if (prev.data.isAuthorize) {
        prev.setData({
          isAuthorize: false
        })
        await this.getLoginStatus()
      }
      if (prev.data.defaultAddress) {
        this.defaultAddress = prev.data.defaultAddress
        this.userShippingAddressId = this.defaultAddress.id
        this.setState({})
      }
    }
  }
  goToAbout() {
    Taro.navigateTo({
      url: '/pages/index/about'
    })
  }

  gotoAddrss() {
    Taro.navigateTo({ url: '/pages/profile/address/index?prev=index' })
  }

  render() {
    return (
      <View className='index-wrap'>
        <View className='about-btn' onClick={this.goToAbout.bind(this)}></View>
        {(!this.cartNowItems || !this.cartNowItems.length) &&
          <View className='chose-box'>
            <View className='chose-cell' onClick={this.gotoMall.bind(this, 0)}>
              {/*<View className='chose-bd'>
                <View className='tit'>原谅我呗</View>
                <View className='disc'>点击这里，帮对方挑选礼物</View>
              </View>
              <View className='chose-ft'>
                <AtIcon value='chevron-right' size='24' color='#bb9e7d' />
              </View>*/}
            </View>
            <View className='chose-cell chose-cell-2' onClick={this.gotoMall.bind(this, 1)}>
              {/*<View className='chose-bd'>
                <View className='tit'>原谅你呗</View>
                <View className='disc'>点击这里，给自己挑选礼物</View>
              </View>
              <View className='chose-ft'>
                <AtIcon value='chevron-right' size='24' color='#bb9e7d' />
              </View>*/}
            </View>
          </View>
        }
        {this.cartNowItems && this.cartNowItems.length &&
          <View className='cart-box'>
            <ScrollView
              className='scrollview'
              scrollY
              scrollWithAnimation
            >
              {this.cartNowItems.map((item) => (
                <View className='cart-cell'>
                  <View className='cart-hd'>
                    <Image mode='aspectFill' src={item.featuredImageUrl} />
                  </View>
                  <View className='cart-bd'>
                    <View className='tit'>{item.productName}</View>
                    <View className='p'>{item.skuName}</View>
                    <View className='disc'>
                      <Text>￥{item.price}</Text>
                      <AtInputNumber
                        type='number'
                        min={0}
                        max={10}
                        step={1}
                        value={item.quantity}
                        onChange={this.handleChange.bind(this, item)}
                        onBlur={this.blurChange}
                      />
                    </View>
                  </View>
                </View>
              ))}
            </ScrollView>

            <View className='cart-bar'>
              <Text>共 {this.cartNowItems.length} 件</Text>
              <Text className='add-link' onClick={this.gotoMall.bind(this, this.type)}>继续添加&gt;</Text>
            </View>
          </View>
        }


        <View className='index-panel'>
          <View className='index-panel-header'>传达心意</View>
          <View className='index-panel-body'>
            <AtTextarea
              className='index-area'
              placeholderClass='area-placeholder'
              value={this.remark}
              onChange={this.handleRemark.bind(this)}
              maxLength='2000'
              count={false}
              placeholder='对Ta说......'
            />
          </View>
        </View>
        {
          this.cartNowItems && this.cartNowItems.length &&
          <View className='index-price'>
            <Text className='sm'>￥</Text>
            <Text className='price'>{this.totalPrice}</Text>
          </View>
        }


        {this.type == 1 && !this.userShippingAddressId && (
          <View className='no-address' onClick={this.gotoAddrss}>
            <AtButton type='primary' size='small'><AtIcon value='map-pin' size='16' />添加收货地址</AtButton>
          </View>
        )}
        {
          this.userShippingAddressId > 0 &&
          <View className='order-address'>
            {
              this.defaultAddress.receiptUserName &&
              <View className='address-item ratina-bd bd-b'>
                <View className='addr-hd'>
                  <Text className='name'>{this.defaultAddress.receiptUserName}</Text>
                </View>
                <View className='addr-bd'>
                  <Text className='tel'>{this.defaultAddress.mobilephone}</Text>
                  <Text className='addr-disc'>{this.defaultAddress.areaCodeDisplayName}{this.defaultAddress.address}</Text>
                </View>
              </View>
            }
          </View>
        }

        <AtForm className='normal-form' reportSubmit onSubmit={this.commit.bind(this)}>
          <View className='index-btn-wrap'>
            <AtButton type='primary' formType='submit'>立即给Ta</AtButton>
            <View className='disc'>但愿你和Ta的笑容里有着相同的内容...</View>
          </View>
        </AtForm>
        <AtToast isOpened={this.state.isOpened} text="正在加载" hasMask={true} status="loading"></AtToast>
      </View>
    )
  }
}

export default Index
